Module 5: Using EventBridge and SNS to Decouple Components

Developing Serverless Solutions on AWS - Live Session Guide

Module Overview

This module covers asynchronous event-driven patterns using Amazon EventBridge and Amazon SNS to build loosely coupled serverless architectures.

Topics

1. Asynchronous Event Processing

In async invocation, the caller doesn't wait for the function to finish. Lambda queues the event and processes it independently.

Sync vs Async Invocation

AspectSynchronousAsynchronous
Caller behaviorWaits for responseGets 202 Accepted immediately
Retry behaviorCaller retriesLambda retries (0-2 times)
Error handlingError returned to callerDead-letter queue (DLQ) or on-failure destination
SourcesAPI Gateway, SDK invokeEventBridge, SNS, S3, CloudWatch Events

Async Flow

Event Source (EventBridge/SNS) Lambda Service Internal Queue + Retries Lambda Fn (Your code) On-Success Destination On-Failure / DLQ 0-2 retries with backoff

Notifying the Client (Async Patterns)

PatternHow It WorksBest For
Client PollingClient periodically checks status endpointSimple, stateless clients
WebhookServer calls back to a client-provided URLServer-to-server notifications
WebSocketPersistent connection, server pushes updatesReal-time UIs, chat, dashboards

2. Amazon EventBridge

A serverless event bus that connects applications using events from AWS services, SaaS apps, and custom sources.

Key Concepts

ConceptDescription
Event BusRouter that receives events and routes them to targets. Default bus + custom buses.
EventJSON object representing a state change (source, detail-type, detail)
RuleMatches incoming events using event patterns and routes to targets
TargetDestination for matched events (Lambda, SQS, Step Functions, API Gateway, etc.)
Event PatternJSON filter that matches event fields (content-based filtering)
ArchiveStore events for replay later (debugging, reprocessing)
ReplayRe-send archived events to the bus (disaster recovery)
PipesPoint-to-point integration with filtering, enrichment, transformation

Event Structure

{
  "version": "0",
  "id": "12345678-1234-1234-1234-123456789012",
  "source": "com.mycompany.orders",
  "detail-type": "Order Created",
  "account": "123456789012",
  "time": "2024-06-15T10:30:00Z",
  "region": "us-west-2",
  "detail": {
    "orderId": "ORD-987654",
    "department": "billing",
    "amount": 149.99,
    "customer": "user12345"
  }
}

Event Pattern (Rule Filter)

// Match orders from billing or fulfillment departments
{
  "source": ["com.mycompany.orders"],
  "detail-type": ["Order Created"],
  "detail": {
    "department": ["billing", "fulfillment"]
  }
}

EventBridge Targets (20+ supported)

Lambda | SQS | SNS | Step Functions | Kinesis | API Gateway | CloudWatch Logs | CodePipeline | ECS Task | Redshift | API Destinations (any HTTP endpoint) | Another Event Bus (cross-account/region)

3. Amazon SNS (Simple Notification Service)

Fully managed pub/sub messaging service for fan-out to multiple subscribers.

Key Concepts

ConceptDescription
TopicA communication channel - publishers send messages to it
PublisherProduces messages and sends them to a topic
SubscriberReceives messages from a topic (Lambda, SQS, HTTP, email, SMS)
Filter PolicyJSON filter on message attributes - subscribers only get matching messages
Standard TopicBest-effort ordering, at-least-once delivery, massive throughput
FIFO TopicStrict ordering, exactly-once delivery, 300 msg/sec (or 3000 with batching)

SNS Message Filtering

Publisher SNS Topic All messages pass through Lambda A Filter: type = "order" SQS Queue Filter: type = "payment" Lambda C No filter (gets ALL messages) Only orders Only payments Everything

Filter Policy Example

// Subscription filter policy - only receive "billing" department messages
{
  "department": ["billing"],
  "amount": [{"numeric": [">=", 100]}]
}

Nested Serverless Applications (Fan-out Pattern)

One SNS topic can fan-out to multiple independent microservices (search indexing, backup, analytics, notifications) - each runs independently and can fail without affecting others.

4. EventBridge vs Amazon SNS

FeatureEventBridgeAmazon SNS
PatternEvent bus (routing)Pub/Sub (fan-out)
Sources200+ AWS services, SaaS, customAWS services, custom publishers
Targets20+ (Lambda, SQS, Step Functions, API Destinations)Lambda, SQS, HTTP, Email, SMS, mobile push
FilteringContent-based (event pattern - complex matching)Message attribute filtering
Fan-out5 targets per rule (use multiple rules)12.5M subscriptions per topic
OrderingNo ordering guaranteeFIFO topics available
ReplayYes (archive + replay)No built-in replay
SchemaSchema registry + discoveryNo schema management
Cross-accountCross-account/region event busCross-account topic subscriptions
ThroughputRegion-dependent limitsNearly unlimited (Standard)
DLQ supportYes (per target)Yes (can BE the DLQ for Lambda)

When to Use What

Use EventBridge When:

  • Routing events from many sources to different targets
  • Need content-based filtering on event body
  • Integrating with SaaS providers (Shopify, Zendesk, etc.)
  • Need event archive and replay
  • Building event-driven microservices with schema registry
  • Cross-account event routing

Use SNS When:

  • Wide fan-out to many subscribers (thousands)
  • Need FIFO ordering guarantee
  • Sending notifications (email, SMS, push)
  • Simple pub/sub without complex routing
  • Need massive throughput (millions msg/sec)
  • Using as DLQ for Lambda async failures

5. Live Demo: EventBridge Rule + Lambda Target

Step 1: Create a custom event bus

aws events create-event-bus --name demo-orders-bus --region us-west-2

Step 2: Create a Lambda function (target)

# handler.py
import json

def handler(event, context):
    print(f"Received event: {json.dumps(event)}")
    order_id = event.get("detail", {}).get("orderId", "unknown")
    dept = event.get("detail", {}).get("department", "unknown")
    return {"statusCode": 200, "body": f"Processed order {order_id} from {dept}"}

Step 3: Create a rule with event pattern

aws events put-rule \
  --name billing-orders-rule \
  --event-bus-name demo-orders-bus \
  --event-pattern '{
    "source": ["com.mycompany.orders"],
    "detail": {
      "department": ["billing"]
    }
  }' \
  --state ENABLED

Step 4: Add Lambda as target

aws events put-targets \
  --rule billing-orders-rule \
  --event-bus-name demo-orders-bus \
  --targets "Id"="lambda-target","Arn"="arn:aws:lambda:us-west-2:ACCOUNT:function:order-processor"

Step 5: Send a test event

aws events put-events --entries '[
  {
    "Source": "com.mycompany.orders",
    "DetailType": "Order Created",
    "Detail": "{\"orderId\":\"ORD-001\",\"department\":\"billing\",\"amount\":250}",
    "EventBusName": "demo-orders-bus"
  }
]'

Step 6: Check Lambda logs

aws logs tail /aws/lambda/order-processor --follow

Step 7: Send a non-matching event (should NOT trigger Lambda)

aws events put-events --entries '[
  {
    "Source": "com.mycompany.orders",
    "DetailType": "Order Created",
    "Detail": "{\"orderId\":\"ORD-002\",\"department\":\"shipping\",\"amount\":50}",
    "EventBusName": "demo-orders-bus"
  }
]'
# This event won't match the rule (department != "billing")

6. What's New (2024-2025 Updates)

7. Module Summary

Key Takeaways

  • Async events don't wait - caller gets immediate acknowledgment
  • Lambda retries async events 0-2 times automatically
  • EventBridge = event routing with content-based filtering + 200+ sources
  • SNS = pub/sub fan-out with massive scale + FIFO option
  • Both support filtering to reduce unnecessary invocations
  • EventBridge has archive/replay; SNS has wider fan-out + FIFO
  • Use destinations and DLQs for error handling in async flows

Architecture Patterns

  • Event-driven microservices - EventBridge bus per domain
  • Fan-out processing - SNS to multiple SQS queues
  • Cross-account events - EventBridge cross-account rules
  • SaaS integration - EventBridge partner sources
  • Async API responses - WebSocket + EventBridge
  • Event replay/debugging - Archive + replay failed events

Developing Serverless Solutions on AWS - Module 5 | Live Session Guide

Last updated: June 2026